package com.hf.action;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import org.apache.struts2.ServletActionContext;

import tool.ClientTool;
import tool.HtmlTool;
import tool.JsonTool;
import tool.StringTool;
import tool.TimeTool;

import com.base.bean.*;
import com.base.dao.*;
import com.base.domain.ClientDetail;
import com.base.service.*;
import com.hf.bean.ClientFilter;
import com.hf.bean.SimpleAddress;

public class ClientAction4 extends BaseAction {
	
	private Integer pageNo,pageSize,totalPage;		//页数  每页几条  共多少页
	private List<ClientDetail> clientList;
	
	private String cjsons;			//clientList转化为json 供kh_show2.jsp(客户详细信息)使用
	
	private Integer orderCon;		//排序条件
	private boolean isDesc;			//是否逆序

	private String phone1, phone2, phone3;
	private Integer phone1Id, phone2Id, phone3Id;

	private String phones, addNames, addCodes; // 分别以"|"分割
	private Integer cid; // 客户id值，在修改的时候会传入
	private String name, comName, memo;
	private String[] chose1, chose2, chose3; // 多选
	private String chose4, chose5; // 单选
	private Integer chose6; // 单选
	private ClientDetail clientDetail;
	


	private ClientFilter clientFilter; // 用于验证客户信息以及生成sellplan时间
	private AddressService as = AddressService.getInstance();
	private ClientService cs = ClientService.getInstance(); // 私有无geter seter
	
	public ClientAction4() {

	}
	
	
	/**
	 * 客户按id显示
	 * @return
	 */
	public String show(){
		this.cid=98;	//实际替换
		ClientBase cb=cs.getClientBaseDao().findByHql("from ClientBase cb where cb.cid="+this.cid).get(0);
		ClientExtend ce=cs.getClientExtendDao().findByHql("from ClientExtend ce where ce.cid="+this.cid).get(0);
		//只取前三条 按时间排序
		List<ClientPhone> cps=cs.getClientPhoneDao().findByPage("from ClientPhone cp where cp.cid="+this.cid+" order by cp.created desc ", 0, 3);
		for(int i=0;i<2;i++){	//补齐3个电话
			if(cps.size()<3){
				ClientPhone cp=new ClientPhone();
				cp.setId(0);
				cp.setPhone("");
				cps.add(cp);
			}else
				break;
		}
		
		clientDetail=new ClientDetail();
		clientDetail.setClientBase(cb);
		clientDetail.setClientExtend(ce);
		clientDetail.setClientPhones(cps);
		clientDetail.setProvinceName(as.getNameByCode(AddressService.ADD_TYPE.PROVINCE, cb.getProvinceId()));
		clientDetail.setCityName(as.getNameByCode(AddressService.ADD_TYPE.CITY, cb.getCityId()));
		clientDetail.setAreaName(as.getNameByCode(AddressService.ADD_TYPE.AREA, cb.getAreaId()));
		return SUCCESS;
	}
	
	/**
	 * 客户修改
	 * @return
	 */
	public String modify(){
		
		
		
		return SUCCESS;
	}
	
	
	/**
	 * 分页显示（默认以达成期限排序）
	 * @return
	 */
	public String showPage(){
		this.cjsons="init";
		User u = new User(1);		//实际替换
		this.pageSize=10;
		this.pageNo=1;
		
		String hql="from ClientExtend ce where ce.owner="+u.getUid()+" order by ce.sellPlan";
//		int total=cs.getClientExtendDao().getTotal("select count(ce) from ClientExtend ce where ce.owner="+u.getUid()+" order by ce.sellPlan desc");
//		totalPage=total/pageSize;
		List<ClientExtend> ceList=cs.getClientExtendDao().findByPage(hql, pageNo*pageSize, pageSize);
		clientList=new ArrayList<ClientDetail>();
		for(ClientExtend ce:ceList){
			ClientBase cb=cs.getClientBaseDao().findByHql("from ClientBase cb where cb.cid="+ce.getCid()).get(0);
			List<ClientPhone> cps=cs.getClientPhoneDao().findByHql("from ClientPhone p where p.cid="+ce.getCid());
			ClientDetail cd=new ClientDetail();
			cd.setClientPhones(cps);
			cd.setClientBase(cb);
			cd.setClientExtend(ce);
			if(ce.getSellPlan()!=null)
				cd.setSellPlanRate(TimeTool.fromTodayRate(ce.getSellPlan(), 100));		//100天作为一个单位
			if(cb.getProvinceId()!=null)	
				cd.setProvinceName(as.getNameByCode(AddressService.ADD_TYPE.PROVINCE, cb.getProvinceId()));
			if(cb.getCityId()!=null)
				cd.setCityName(as.getNameByCode(AddressService.ADD_TYPE.CITY, cb.getCityId()));
			if(cb.getAreaId()!=null)
				cd.setAreaName(as.getNameByCode(AddressService.ADD_TYPE.AREA, cb.getAreaId()));
			
			clientList.add(cd);

		}
		
		this.cjsons=HtmlTool.getInstance().htmlClientDetail(clientList).toString();

		return SUCCESS;
	}
	

	// 新增客户
	public String merge() {

		
		if(phone1==null || name==null)	//没有姓名或电话直接返回
			return SUCCESS;
		
		
		
		// 实际使用时 替换下面这句
		User u = new User(1);
		boolean isOwn = false;
		boolean addIsNotChange = false;
		boolean isNew = false; // 是否是新增的信息

		if (addCodes.equals("0|0|0")) {
			addIsNotChange = true; // 这种情况，不需要更新省市区
		}

		ClientBase clientBase = null;
		ClientExtend clientExtend = null;
		List<ClientPhone> pList = null;

		if (cid != null) {
			clientBase = cs.getClientBaseDao()
					.findByHql("from ClientBase cb where cb.cid=" + cid).get(0);
			clientExtend = cs.getClientExtendDao()
					.findByHql("from ClientBase cb where cb.cid=" + cid).get(0);
			pList = cs.getClientPhoneDao().findByHql(
					"from ClientPhone p where p.cid=" + cid);
			
			if (clientBase.getCreator().equals(u.getUid()))
				isOwn = true;
			
		} else {
			isNew = true;
			isOwn = true;
			clientBase=new ClientBase();
			clientExtend = new ClientExtend();
		}

		
			

		// 将传入的参数赋值给clientBase clientExtend List<clientPhone>
		if (!isNew)
			clientBase.setCid(cid);
		clientBase.setName(name);
		clientBase.setComName(comName);
		if (addIsNotChange == false) {
			String[] _addCodes = addCodes.split("\\|");
			if (_addCodes[0] != "" && _addCodes[0] != null)
				clientBase.setProvinceId(_addCodes[0]);
			if (_addCodes[1] != "" && _addCodes[1] != null)
				clientBase.setCityId(_addCodes[1]);
			if (_addCodes[2] != "" && _addCodes[2] != null)
				clientBase.setAreaId(_addCodes[2]);
		}
		if(this.memo!=null)
			clientExtend.setMemo(memo.trim());
		if(this.chose1!=null)
			clientExtend.setYywjj(StringTool.arrToStr(chose1));
		if(this.chose2!=null)
			clientExtend.setYyzzj(StringTool.arrToStr(chose2));
		if(this.chose3!=null)
			clientExtend.setYgsbType(StringTool.arrToStr(chose3));
		if(this.chose4!=null)
			clientExtend.setClientType(chose4);
		if(this.chose5!=null)
			clientExtend.setIsZan(chose5);
		if(this.chose6!=null){
//			clientExtend.setGjTimeType(chose6);			//注意：这个字段不能赋值
			clientExtend.setSellPlan(TimeTool.nMonthLeater(chose6));
		}

		// pList 赋值过程
		pList = new ArrayList<ClientPhone>();
		if (this.phone1 != null && !this.phone1.trim().equals("")) {
			ClientPhone cp1 = new ClientPhone();
			if (this.phone1Id != null)
				cp1.setId(phone1Id);
			cp1.setPhone(phone1);
			pList.add(cp1);
		}
		if (this.phone2 != null && !this.phone2.trim().equals("")) {
			ClientPhone cp2 = new ClientPhone();
			if (this.phone2Id != null)
				cp2.setId(phone2Id);
			cp2.setPhone(phone2);
			pList.add(cp2);
		}
		if (this.phone3 != null &&  !this.phone3.trim().equals("")) {
				ClientPhone cp3 = new ClientPhone();
				if (this.phone3Id != null)
					cp3.setId(phone3Id);
				cp3.setPhone(phone3);
				pList.add(cp3);

		}

		clientFilter = new ClientFilter(clientBase, clientExtend, pList);
		clientFilter = clientFilter.filtering(clientFilter);

		if (!clientFilter.isChecked()) { // 验证未能通过 tip中说明错误原因
			String[] a = clientFilter.getCheckedResult().split("#");
			if (a[0].equals("N"))
				this.tip = "姓名格式错误<br> ";
			else if (a[0].equals("C"))
				this.tip = "姓名不合法<br> ";
			else if (a[0].equals("E"))
				this.tip = "姓名出现未知错误<br> ";
			else
				this.tip = "姓名验证通过<br> ";

			String[] b = a[1].split(",");
			for (int i = 0; i < b.length; i++) {
				String s = b[i];
				if (s.equals("N"))
					this.tip = tip + "电话" + (i + 1) + "格式错误<br>";
				else if (s.equals("R"))
					this.tip = tip + "电话" + (i + 1) + "已经存在<br> ";
				else if (s.equals("E"))
					this.tip = tip + "电话" + (i + 1) + "出现未知错误<br>  ";
			}
			// 验证信息未能通过
			return SUCCESS;
			}

			// 新增信息
			if (isNew) {
				try {
					this.cid=cs.addClient(clientFilter.getcBase(),clientFilter.getcExtend(), clientFilter.getpList());
				} catch (Exception e) {
					this.tip=tip+"新增客户信息失败";
					e.printStackTrace();
					return SUCCESS;
				}	// 回写cid
				if(cid==0)
					cid=null;
				this.tip = tip + "新增客户信息完毕<br>";
				return SUCCESS;
			}
			// 修改信息 需要先判定是否是自建客户
			if (!isOwn) {
				cs.getClientExtendDao().merge(clientExtend);
				this.tip = tip + "非自建客户只能修改扩展信息<br>";
				return SUCCESS;
			} else { // 修改自建客户信息
				cs.getClientBaseDao().merge(clientBase);
				this.tip = tip + "客户基本信息修改 OK<br>";
				cs.getClientExtendDao().merge(clientExtend);
				this.tip = tip + "客户扩展信息修改 OK<br>";
				for (int i = 0; i < clientFilter.getpList().size(); i++) {
					cs.getClientPhoneDao()
							.merge(clientFilter.getpList().get(i));
					this.tip = tip + "电话" + (i + 1) + "修改 OK<br>";
				}
				// 修改自建客户信息完毕
				return SUCCESS;
			}
		
	}

	
	public String execute() {
		// TODO Auto-generated method stub
		return null;
	}

	// #####################################################################################################

	// #####################################################################################################

	public static void main(String[] args) throws Exception{
		ClientAction4 c=new ClientAction4();
		c.showPage();
		String test=HtmlTool.getInstance().htmlClientDetail(c.getClientList()).toString();
//		System.out.println(JsonTool.obj2json(c.getClientList()));
		System.out.println(test);
	}
	
	

	public String getPhones() {
		return phones;
	}

	public void setPhones(String phones) {
		this.phones = phones;
	}

	public String getAddNames() {
		return addNames;
	}

	public void setAddNames(String addNames) {
		this.addNames = addNames;
	}

	public String getAddCodes() {
		return addCodes;
	}

	public void setAddCodes(String addCodes) {
		this.addCodes = addCodes;
	}

	public Integer getCid() {
		return cid;
	}

	public void setCid(Integer cid) {
		this.cid = cid;
	}

	public String getName() {
		return name;
	}

	public void setName(String name) {
		this.name = name;
	}

	public String getComName() {
		return comName;
	}

	public void setComName(String comName) {
		this.comName = comName;
	}

	public String getMemo() {
		return memo;
	}

	public void setMemo(String memo) {
		this.memo = memo;
	}

	public String[] getChose1() {
		return chose1;
	}

	public void setChose1(String[] chose1) {
		this.chose1 = chose1;
	}

	public String[] getChose2() {
		return chose2;
	}

	public void setChose2(String[] chose2) {
		this.chose2 = chose2;
	}

	public String[] getChose3() {
		return chose3;
	}

	public void setChose3(String[] chose3) {
		this.chose3 = chose3;
	}

	public String getChose4() {
		return chose4;
	}

	public void setChose4(String chose4) {
		this.chose4 = chose4;
	}

	public String getChose5() {
		return chose5;
	}

	public void setChose5(String chose5) {
		this.chose5 = chose5;
	}

	public Integer getChose6() {
		return chose6;
	}

	public void setChose6(Integer chose6) {
		this.chose6 = chose6;
	}

	public ClientFilter getClientFilter() {
		return clientFilter;
	}

	public void setClientFilter(ClientFilter clientFilter) {
		this.clientFilter = clientFilter;
	}

	public String getPhone1() {
		return phone1;
	}

	public void setPhone1(String phone1) {
		this.phone1 = phone1;
	}

	public String getPhone2() {
		return phone2;
	}

	public void setPhone2(String phone2) {
		this.phone2 = phone2;
	}

	public String getPhone3() {
		return phone3;
	}

	public void setPhone3(String phone3) {
		this.phone3 = phone3;
	}

	public Integer getPhone1Id() {
		return phone1Id;
	}

	public void setPhone1Id(Integer phone1Id) {
		this.phone1Id = phone1Id;
	}

	public Integer getPhone2Id() {
		return phone2Id;
	}

	public void setPhone2Id(Integer phone2Id) {
		this.phone2Id = phone2Id;
	}

	public Integer getPhone3Id() {
		return phone3Id;
	}

	public void setPhone3Id(Integer phone3Id) {
		this.phone3Id = phone3Id;
	}


	public Integer getPageNo() {
		return pageNo;
	}


	public void setPageNo(Integer pageNo) {
		this.pageNo = pageNo;
	}

	public Integer getPageSize() {
		return pageSize;
	}


	public void setPageSize(Integer pageSize) {
		this.pageSize = pageSize;
	}


	public Integer getTotalPage() {
		return totalPage;
	}


	public void setTotalPage(Integer totalPage) {
		this.totalPage = totalPage;
	}


	public List<ClientDetail> getClientList() {
		return clientList;
	}

	public void setClientList(List<ClientDetail> clientList) {
		this.clientList = clientList;
	}


	public Integer getOrderCon() {
		return orderCon;
	}


	public void setOrderCon(Integer orderCon) {
		this.orderCon = orderCon;
	}


	public boolean isDesc() {
		return isDesc;
	}


	public void setDesc(boolean isDesc) {
		this.isDesc = isDesc;
	}


	public String getCjsons() {
		return cjsons;
	}


	public void setCjsons(String cjsons) {
		this.cjsons = cjsons;
	}


	public ClientDetail getClientDetail() {
		return clientDetail;
	}


	public void setClientDetail(ClientDetail clientDetail) {
		this.clientDetail = clientDetail;
	}





}
